const express = require('express');
const router = express.Router();
const multer = require('multer');
const fs = require('fs');
const PNG = require('pngjs').PNG;
const path = require('path');
const GlobalUtil = require('../Util/GlobalUtil');

const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
router.use(express.raw({ type: 'application/octet-stream', limit: '10mb' }));

const mimeTypeToExtension = {
    'image/jpeg': '.jpg',
    'image/png': '.png',
    'image/gif': '.gif'
    // 可以根据需要添加更多的映射
};

// 修改头像
router.post('/uploadAvatar', upload.single('Avatar'), async (req, res) => {
    try {
        const token = req.headers.authorization;
        const decoded = await GlobalUtil.asyncVerify(token);

        if (!req.file) {
            return res.status(400).send('No file (Blob) uploaded.');
        }
        // 获取文件扩展名
        const fileExtension = mimeTypeToExtension[req.file.mimetype] || '.unknown';
        // 生成唯一的文件名
        const fileName = `${Date.now()}${fileExtension}`;
        // 定义保存文件的路径
        const filePath = path.join(__dirname, '../../Data/Avatar', fileName);

        // 将文件数据写入本地文件
        fs.writeFile(filePath, req.file.buffer, async (err) => {
            if (err) {
                console.error(err);
                return res.status(500).send('Error saving file.');
            }
            // 更新数据库头像url
            avatar_url = `/Avatar/${fileName}`;
            const sql = "UPDATE userdata SET avatar_url = ? WHERE user_id = ?";
            const result = await GlobalUtil.asyncQuery(sql, [avatar_url, decoded.user_id]);
            res.status(200).send({msg: '修改头像成功！'});
        });
    } catch (error) {
        console.error(error);
        res.status(500).send('Internal Server Error');
    }
});

//安卓平台通过Uint8Array上传头像
router.post('/uploadAvatarByAndroid', async (req, res) => {
    try {
        const token = req.headers.authorization;
        const decoded = await GlobalUtil.asyncVerify(token);
        const Uint8Data = req.body;
        const pixels = Uint8Data;
        //定义文件名和文件路径
        const fileName = Date.now() + ".png";
        const filePath = path.join(__dirname, '../../Data/Avatar', fileName);
        //图像的宽高
        const width = 185;
        const height = 185;
        //创建PNG对象
        const png = new PNG({
            width: width,
            height: height,
        });
        //验证图片宽高与像素是否匹配
        if (pixels.length !== width * height * 4) {
            throw new Error("Invalid pixel data length");
        }
        // 将像素数据复制到 PNG 对象中
        for (let y = 0; y < height; y++) {
            for (let x = 0; x < width; x++) {
                const idx = (width * y + x) << 2; // 计算像素索引
                png.data[idx] = pixels[idx];     // R
                png.data[idx + 1] = pixels[idx + 1]; // G
                png.data[idx + 2] = pixels[idx + 2]; // B
                png.data[idx + 3] = pixels[idx + 3]; // A
            }
        }
        // 将 PNG 写入文件
        png.pack().pipe(fs.createWriteStream(filePath))
            .on('finish', async () => {
                // 更新数据库头像url
                avatar_url = `/Avatar/${fileName}`;
                const sql = "UPDATE userdata SET avatar_url = ? WHERE user_id = ?";
                const result = await GlobalUtil.asyncQuery(sql, [avatar_url, decoded.user_id]);
                res.status(200).send({msg: '修改头像成功！'});
            })
            .on('error', (err) => {
                console.error('Error saving PNG file:', err);
                res.status(500).send('Error saving PNG file');
            });
    } catch (error) {
        console.error(error);
        res.status(500).send('Internal Server Error');
    }
})

module.exports = router;